package com.example.onlinemonitoring.comCenter;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.dao.DtshistoryMapper;
import com.example.onlinemonitoring.dao.DtspartitionMapper;
import com.example.onlinemonitoring.dao.DtsphistoryMapper;
import com.example.onlinemonitoring.dao.DtssensorMapper;
import com.example.onlinemonitoring.model.*;
import com.example.onlinemonitoring.serviceImpl.DtssensorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * 分布式光纤
 */
@Service("dtsCom")
@Scope("prototype")
public class DtsCom extends CommPortManager {
    @Autowired
    private DtssensorMapper dtssensormapper;
    @Autowired
    private DtshistoryMapper dtshistorymapper;
    @Autowired
    private DtsphistoryMapper dtsphistorymapper;
    @Autowired
    private DtspartitionMapper dtspartitionmapper;
    @Autowired
    private DtssensorServiceImpl dtsserviceimpl;
    String strs = "";
    Long id[] = new Long[1024];
    int[] isbroken = new int[17];
    int[] brokenposition = new int[17];

    @Override
    public void receiveData(String str) {
        if (str.length() < 100) {
            setText(str);
        }

        if (str.length() > 5) {
            if (!str.substring(0, 4).equals("CCAA")) {
                strs += str;
            } else {
                strs = str;
            }
            System.out.println(checksum(strs.substring(0, strs.length() - 2)));
            if (checksum(strs.substring(0, strs.length() - 2)).equals(strs.substring(strs.length() - 2))) {
                str = strs;
                strs = "";
            } else {
                return;
            }
        } else {
            return;
        }
        setText(str.substring(0, 20));
        int chunk = parseHex4(str.substring(16, 18)) + 1;
        switch (str.substring(14, 16)) {
            case "07":
                str = str.substring(26, str.length() - 2);
                loadAllTemperWithBroken(str, chunk, -1);
                break;
            case "0D":
                setText(str);
                str = str.substring(16, str.length() - 2);
                loadBroken(str);
                break;
            case "14":
                if (str.substring(26, 28).equals("01")) {
                    int pos = parseHex4(str.substring(28, 30)) * 256 * 256 * 256
                            + parseHex4(str.substring(30, 32)) * 256 * 256
                            + parseHex4(str.substring(32, 34)) * 256
                            + parseHex4(str.substring(34, 36));
                    str = str.substring(36, str.length() - 2);
                    loadAllTemperWithBroken(str, chunk, pos);
                } else {
                    str = str.substring(36, str.length() - 2);
                    loadAllTemperWithBroken(str, chunk, -1);
                }
                break;

            default:
                break;
        }
    }

    private void loadBroken(String str) {
        System.out.println(str + " len:" + str.length());
        int len = str.length();
        for (int i = 0; i < len * 3 / 6; i += 3) {
            isbroken[i / 3 + 1] = Integer.parseInt(str.substring(i * 2, i * 2 + 2), 16);
            System.out.println("通道" + (i / 3 + 1) + "是否断纤：" + (isbroken[i / 3 + 1] == 0 ? "否" : "是"));
            brokenposition[i / 3 + 1] = Integer.parseInt(str.substring(i * 2 + 2, i * 2 + 4), 16) * 256
                    + Integer.parseInt(str.substring(i * 2 + 4, i * 2 + 6), 16);
        }
    }

    /**
     * 
     * @param str   报文
     * @param chunk 通道号
     * @param pos   断纤位置，如果该值为-1则不计算
     */
    private void loadAllTemperWithBroken(String str, int chunk, int pos) {
        reSend[chunk] = 0;
        addrindex++;

        int datalen = str.length() / 4;// 温度数据总长度
        float[] temperarray = new float[datalen];// 温度数组
        float[] differarray = new float[datalen];// 差温数组
        StringBuilder temperstr = new StringBuilder();// 要写入数据库的温度拼接字符串
        Dtssensor dts = new Dtssensor();
        dts.setStationid(ad.getStationid());
        dts.setDevicegroup(ad.getDevicegroup());
        dts.setIpaddr(ad.getIp());
        dts.setChunk(chunk);
        dts = dtssensormapper.selectsinglebytotal(dts);
        if (dts == null) {
            setText("<" + ad.getIp() + ">" + "通道" + chunk + "不存在，请联系维护人员！");
            return;
        }
        if (dts.getOldtimersp() == null) {
            setText("<" + dts.getIpaddr() + ">" + "差温时间间隔没有设置！");
            return;
        }
        Date dt = new Date();
        long oldtime = 0l;
        long nowtime = 0l;
        for (int i = 0; i < datalen; i++) {
            temperarray[i] = (parseHex4(str.substring(i * 4, 2 + i * 4)) * 256
                    + parseHex4(str.substring(2 + i * 4, 4 + i * 4))) / 10f;
            temperstr.append(temperarray[i] + ",");
        }
        try {
            String[] oldtemperstr = new String[datalen];
            nowtime = HexUtil.todate(dt).getTime();
            oldtemperstr = dts.getOlddata().split(",");
            oldtime = dts.getOlddatatime().getTime();
            // 差温比较必须每隔至少30秒以上才好判断
            // 不在for循环内嵌套if是为了减少运行次数，优化速度
            if (nowtime - oldtime > isnull(dts.getOldtimersp()) * 1000) {// 时间到了，进行差温比较
                for (int i = 0; i < datalen; i++) {
                    differarray[i] = temperarray[i] - Float.parseFloat(oldtemperstr[i]);
                }
                dts.setOlddata(temperstr.toString());
                dts.setOlddatatime(dt);
            }
        } catch (Exception e) {
            setText("<" + dts.getIpaddr() + ">" + "总站数据写入失败,正在执行初始化操作...");
            try {
                dts.setOlddata(temperstr.toString());
                dts.setOlddatatime(dt);
                dts.setData(temperstr.toString());
                dts.setLength(datalen);
                dts.setLastdatatime(dt);
                dts.setLastcommunicationstatus(0);
                dts.setDatalength(datalen);
                dtssensormapper.updateByPrimaryKeySelective(dts);
                return;
            } catch (Exception e2) {
                setText("<" + dts.getIpaddr() + ">" + "初始化失败...");
            }
        }

        dts.setData(temperstr.toString());
        dts.setLength(datalen);
        dts.setLastdatatime(dt);
        dts.setLastcommunicationstatus(isbroken[chunk] == 0 ? 0 : 1);
        dts.setDatalength(datalen);
        dts.setLasthisdatatime(addHistory(dts));
        dtssensormapper.updateByPrimaryKeySelective(dts);

        // 分区循环开始
        Dtspartition dtsp = new Dtspartition();
        dtsp.setStationid(ad.getStationid());
        dtsp.setDevicegroup(ad.getDevicegroup());
        dtsp.setIpaddr(ad.getIp());
        dtsp.setChunk(chunk);
        List<Dtspartition> dtspl = dtspartitionmapper.selectbytotal(dtsp);
        for (int m = 0; m < dtspl.size(); m++) {
            dtsp = dtspl.get(m);
            if (dtsp.getPartitionname() == null) {
                dtsp.setPartitionname("<" + dts.getIpaddr() + ">" + "未命名分区");
            }
            if (dtsp.getEndposition() == null || dtsp.getStartposition() == null) {
                setText("<" + dts.getIpaddr() + ">" + "分区" + dtsp.getPartitionname() + "未设置起点或终点！");
                continue;
            }
            if (dtsp.getTemperalarmvalue() == null || dtsp.getTemperalarmrelievevalue() == null
                    || dtsp.getTemperwarnvalue() == null || dtsp.getTemperwarnrelievevalue() == null ||
                    dtsp.getDifferalarmvalue() == null || dtsp.getDifferalarmrelievevalue() == null
                    || dtsp.getDifferwarnvalue() == null || dtsp.getDifferwarnrelievevalue() == null) {
                setText("<" + dts.getIpaddr() + ">" + "分区" + dtsp.getPartitionname()
                        + "未设置报警值或预警值，当前使用标准报警值预警值代替！请尽快设置！");
                dtsp.setTemperalarmvalue(10f);
                dtsp.setTemperalarmrelievevalue(1f);
                dtsp.setTemperwarnvalue(1f);
                dtsp.setTemperwarnrelievevalue(1f);
                dtsp.setDifferalarmvalue(10f);
                dtsp.setDifferalarmrelievevalue(1f);
                dtsp.setDifferwarnvalue(1f);
                dtsp.setDifferwarnrelievevalue(1f);
            }
            int addr = Integer.parseInt(dtsp.getIpaddr().split("\\.")[3]);
            int plen = Math.round(dtsp.getEndposition() - dtsp.getStartposition()) * 2;
            StringBuilder pdatastr = new StringBuilder();// 分区数据
            StringBuilder temperalarmstr = new StringBuilder();// 分区定温报警字符串
            StringBuilder differalarmstr = new StringBuilder();// 分区差温报警字符串
            String[] temperalarmlevelstr = new String[plen]; // 上次分区定温报警
            String[] differalarmlevelstr = new String[plen]; // 上次分区差温报警
            Float maximumtemp = 0f;
            Float averagetemp = 0f;
            int alarmlevel = 0;
            StringBuilder alarmmessage = new StringBuilder();

            if (ad.getBrand().equals("16")) {
                if (isbroken[chunk] == 1) {
                    alarmlevel = 2;
                    alarmmessage.append("分区" + dtsp.getPartitionname() + "位置" + brokenposition[chunk] + "断纤报警");
                    GetNormalAlarm("分区" + dtsp.getPartitionname() + "位置", dtsp.getDevicegroup(), addr, chunk,
                            dtsp.getPointname(),
                            "分区" + dtsp.getPartitionname() + "位置" + brokenposition[chunk] + "断纤报警", true);
                } else {
                    GetNormalAlarm("分区" + dtsp.getPartitionname() + "位置", dtsp.getDevicegroup(), addr, chunk,
                            dtsp.getPointname(), "", false);
                }
            } else {
                if (pos != -1) {
                    alarmlevel = 2;
                    alarmmessage.append("分区" + dtsp.getPartitionname() + "位置" + pos / 2f + "断纤报警");
                    GetNormalAlarm("分区" + dtsp.getPartitionname() + "位置", dtsp.getDevicegroup(), addr, chunk,
                            dtsp.getPointname(),
                            "分区" + dtsp.getPartitionname() + "位置" + pos / 2f + "断纤报警", true);
                } else {
                    GetNormalAlarm("分区" + dtsp.getPartitionname() + "位置", dtsp.getDevicegroup(), addr, chunk,
                            dtsp.getPointname(), "", false);
                }
            }
            int tlen = 0;
            try {
                temperalarmlevelstr = dtsp.getTemperalarmlevel().split(",");
                differalarmlevelstr = dtsp.getDifferalarmlevel().split(",");

                for (int i = 0; i < plen; i++) {
                    int index = i + Math.round(dtsp.getStartposition() * 2);
                    if (index >= datalen) {
                        break;
                    }
                    if (isbroken[chunk] == 1) {// 断纤以后，后面的不计算
                        if (i >= brokenposition[chunk] * 2) {
                            break;
                        }
                    }
                    if (temperarray[index] > 500 || temperarray[index] < -50) {
                        break;
                    }
                    float alarmlen = (index / 2f - isnull(dts.getMachinelength()));// 减去机内长度
                    int temperAlarmStatus = 0;
                    int differAlarmStatus = 0;
                    if (pos != -1 && index > (pos - 5)) {
                    } else {
                        temperAlarmStatus = GetAlarmStatus(temperarray[index], dtsp.getTemperalarmvalue(),
                                dtsp.getTemperalarmrelievevalue(), dtsp.getTemperwarnvalue(),
                                dtsp.getTemperwarnrelievevalue(), Integer.parseInt(temperalarmlevelstr[i]), true,
                                "分区" + dtsp.getPartitionname() + "位置" + alarmlen + "m定温", dtsp.getDevicegroup(), addr,
                                dtsp.getPointname(), chunk);
                        differAlarmStatus = GetAlarmStatus(differarray[index], dtsp.getDifferalarmvalue(),
                                dtsp.getDifferalarmrelievevalue(), dtsp.getDifferwarnvalue(),
                                dtsp.getDifferwarnrelievevalue(), Integer.parseInt(differalarmlevelstr[i]), true,
                                "分区" + dtsp.getPartitionname() + "位置" + alarmlen + "m差温", dtsp.getDevicegroup(), addr,
                                dtsp.getPointname(), chunk);
                        alarmlevel = HexUtil.MAX(new int[] { alarmlevel, temperAlarmStatus, differAlarmStatus });
                    }

                    temperalarmstr.append(temperAlarmStatus + ",");
                    differalarmstr.append(differAlarmStatus + ",");
                    alarmmessage.append(
                            GetAlarmMessage(temperAlarmStatus,
                                    "分区" + dtsp.getPartitionname() + "位置" + alarmlen + "m定温"));
                    alarmmessage.append(
                            GetAlarmMessage(differAlarmStatus,
                                    "分区" + dtsp.getPartitionname() + "位置" + alarmlen + "m差温"));
                    pdatastr.append(temperarray[index] + ",");
                    averagetemp += temperarray[index];
                    tlen++;
                    maximumtemp = maximumtemp > temperarray[index] ? maximumtemp : temperarray[index];
                }
            } catch (Exception e) {
                // 分区初始化
                setText(e.toString());
                setText("<" + dts.getIpaddr() + ">" + "分区数据写入失败,正在执行初始化操作...");
                for (int i = 0; i < plen; i++) {
                    if (i + Math.round(dtsp.getStartposition() * 2) >= datalen) {
                        break;
                    }
                    temperalarmstr.append("0,");
                    differalarmstr.append("0,");
                    pdatastr.append(temperarray[i + Math.round(dtsp.getStartposition() * 2)] + ",");
                }
                dtsp.setDatalength(plen);
                dtsp.setData(pdatastr.toString());
                dtsp.setTemperalarmlevel(temperalarmstr.toString());
                dtsp.setDifferalarmlevel(differalarmstr.toString());
                dtspartitionmapper.updateByPrimaryKeySelective(dtsp);
                continue;
            }
            dtsp.setMaximumtemp(maximumtemp);
            if (tlen != 0) {
                dtsp.setAveragetemp(averagetemp / tlen);
            } else {
                dtsp.setAveragetemp(0f);
            }

            dtsp.setDatalength(plen);
            dtsp.setData(pdatastr.toString());
            dtsp.setTemperalarmlevel(temperalarmstr.toString());
            dtsp.setDifferalarmlevel(differalarmstr.toString());
            dtsp.setLastalarmlevel(alarmlevel);
            dtsp.setLastalarmmessage(alarmmessage.toString());
            dtsp.setLasthisdatatime(paddHistory(dtsp));
            dtsp.setLastdatatime(dt);
            dtsp.setPartitionname(null);
            dtsp.setStartposition(null);
            dtsp.setEndposition(null);
            dtsp.setTemperalarmvalue(null);
            dtsp.setTemperalarmrelievevalue(null);
            dtsp.setTemperwarnvalue(null);
            dtsp.setTemperwarnrelievevalue(null);
            dtsp.setDifferalarmvalue(null);
            dtsp.setDifferalarmrelievevalue(null);
            dtsp.setDifferwarnvalue(null);
            dtsp.setDifferwarnrelievevalue(null);
            dtspartitionmapper.updateByPrimaryKeySelective(dtsp);
        }
    }

    /**
     * 
     * @param str        报文
     * @param chunk      通道号
     * @param updateTime 断纤位置，如果该值为-1则不计算
     */
    private void loadAllTemperAboutDegang(String str, int chunk, float avgValue, float maxValue, Date dt) {
        reSend[chunk] = 0;
        addrindex++;

        String[] degangtemper = str.split(",");
        int datalen = degangtemper.length;
        StringBuilder temperstr = new StringBuilder(str);// 要写入数据库的温度拼接字符串
        float[] temperarray = new float[datalen];// 温度数组
        float[] differarray = new float[datalen];// 差温数组

        Dtssensor dts = new Dtssensor();
        dts.setStationid(ad.getStationid());
        dts.setDevicegroup(ad.getDevicegroup());
        dts.setIpaddr(ad.getIp());
        dts.setChunk(chunk);
        dts = dtssensormapper.selectsinglebytotal(dts);
        if (dts == null) {
            setText("<" + ad.getIp() + ">" + "通道" + chunk + "不存在，请联系维护人员！");
            return;
        }
        if (dts.getOldtimersp() == null) {
            setText("<" + dts.getIpaddr() + ">" + "差温时间间隔没有设置！");
            return;
        }
        long oldtime = 0l;
        long nowtime = 0l;
        for (int i = 0; i < degangtemper.length; i++) {
            temperarray[i] = Float.parseFloat(degangtemper[i]);
        }
        try {
            String[] oldtemperstr = new String[datalen];
            nowtime = HexUtil.todate(dt).getTime();
            oldtemperstr = dts.getOlddata().split(",");
            oldtime = dts.getOlddatatime().getTime();
            // 差温比较必须每隔至少30秒以上才好判断
            // 不在for循环内嵌套if是为了减少运行次数，优化速度
            if (nowtime - oldtime > isnull(dts.getOldtimersp()) * 1000) {// 时间到了，进行差温比较
                for (int i = 0; i < datalen; i++) {
                    differarray[i] = temperarray[i] - Float.parseFloat(oldtemperstr[i]);
                }
                dts.setOlddata(temperstr.toString());
                dts.setOlddatatime(dt);
            }
        } catch (Exception e) {
            setText("<" + dts.getIpaddr() + ">" + "总站数据写入失败,正在执行初始化操作...");
            try {
                dts.setOlddata(temperstr.toString());
                dts.setOlddatatime(dt);
                dts.setData(temperstr.toString());
                dts.setLength(datalen);
                dts.setLastdatatime(dt);
                dts.setLastcommunicationstatus(0);
                dts.setDatalength(datalen);
                dtssensormapper.updateByPrimaryKeySelective(dts);
                return;
            } catch (Exception e2) {
                setText("<" + dts.getIpaddr() + ">" + "初始化失败...");
            }
        }

        dts.setData(temperstr.toString());
        dts.setLength(datalen);
        dts.setLastdatatime(dt);
        dts.setLastcommunicationstatus(isbroken[chunk] == 0 ? 0 : 1);
        dts.setDatalength(datalen);
        dts.setLasthisdatatime(addHistory(dts));
        dtssensormapper.updateByPrimaryKeySelective(dts);

        // 分区循环开始
        Dtspartition dtsp = new Dtspartition();
        dtsp.setStationid(ad.getStationid());
        dtsp.setDevicegroup(ad.getDevicegroup());
        dtsp.setIpaddr(ad.getIp());
        dtsp.setChunk(chunk);
        List<Dtspartition> dtspl = dtspartitionmapper.selectbytotal(dtsp);
        for (int m = 0; m < dtspl.size(); m++) {
            dtsp = dtspl.get(m);
            if (dtsp.getPartitionname() == null) {
                dtsp.setPartitionname("<" + dts.getIpaddr() + ">" + "未命名分区");
            }
            if (dtsp.getEndposition() == null || dtsp.getStartposition() == null) {
                setText("<" + dts.getIpaddr() + ">" + "分区" + dtsp.getPartitionname() + "未设置起点或终点！");
                continue;
            }
            if (dtsp.getTemperalarmvalue() == null || dtsp.getTemperalarmrelievevalue() == null
                    || dtsp.getTemperwarnvalue() == null || dtsp.getTemperwarnrelievevalue() == null ||
                    dtsp.getDifferalarmvalue() == null || dtsp.getDifferalarmrelievevalue() == null
                    || dtsp.getDifferwarnvalue() == null || dtsp.getDifferwarnrelievevalue() == null) {
                setText("<" + dts.getIpaddr() + ">" + "分区" + dtsp.getPartitionname()
                        + "未设置报警值或预警值，当前使用标准报警值预警值代替！请尽快设置！");
                dtsp.setTemperalarmvalue(10f);
                dtsp.setTemperalarmrelievevalue(1f);
                dtsp.setTemperwarnvalue(1f);
                dtsp.setTemperwarnrelievevalue(1f);
                dtsp.setDifferalarmvalue(10f);
                dtsp.setDifferalarmrelievevalue(1f);
                dtsp.setDifferwarnvalue(1f);
                dtsp.setDifferwarnrelievevalue(1f);
            }
            int addr = Integer.parseInt(dtsp.getIpaddr().split("\\.")[3]);
            int plen = Math.round(dtsp.getEndposition() - dtsp.getStartposition());
            StringBuilder pdatastr = new StringBuilder();// 分区数据
            StringBuilder temperalarmstr = new StringBuilder();// 分区定温报警字符串
            StringBuilder differalarmstr = new StringBuilder();// 分区差温报警字符串
            String[] temperalarmlevelstr = new String[plen]; // 上次分区定温报警
            String[] differalarmlevelstr = new String[plen]; // 上次分区差温报警
            Float maximumtemp = 0f;
            Float averagetemp = 0f;
            int alarmlevel = 0;
            StringBuilder alarmmessage = new StringBuilder();

            GetNormalAlarm("分区" + dtsp.getPartitionname() + "位置", dtsp.getDevicegroup(), addr, chunk,
                    dtsp.getPointname(), "", false);
            int tlen = 0;
            try {
                temperalarmlevelstr = dtsp.getTemperalarmlevel().split(",");
                differalarmlevelstr = dtsp.getDifferalarmlevel().split(",");

                for (int i = 0; i <= plen; i++) {
                    int index = i + Math.round(dtsp.getStartposition());
                    if (index > datalen) {
                        break;
                    }
                    if (temperarray[index] > 500 || temperarray[index] < -50) {
                        break;
                    }
                    float alarmlen = (index - isnull(dts.getMachinelength()));// 减去机内长度
                    int temperAlarmStatus = 0;
                    int differAlarmStatus = 0;
                    temperAlarmStatus = GetAlarmStatus(temperarray[index], dtsp.getTemperalarmvalue(),
                            dtsp.getTemperalarmrelievevalue(), dtsp.getTemperwarnvalue(),
                            dtsp.getTemperwarnrelievevalue(), Integer.parseInt(temperalarmlevelstr[i]), true,
                            "分区" + dtsp.getPartitionname() + "位置" + alarmlen + "m定温", dtsp.getDevicegroup(), addr,
                            dtsp.getPointname(), chunk);
                    differAlarmStatus = GetAlarmStatus(differarray[index], dtsp.getDifferalarmvalue(),
                            dtsp.getDifferalarmrelievevalue(), dtsp.getDifferwarnvalue(),
                            dtsp.getDifferwarnrelievevalue(), Integer.parseInt(differalarmlevelstr[i]), true,
                            "分区" + dtsp.getPartitionname() + "位置" + alarmlen + "m差温", dtsp.getDevicegroup(), addr,
                            dtsp.getPointname(), chunk);
                    alarmlevel = HexUtil.MAX(new int[] { alarmlevel, temperAlarmStatus, differAlarmStatus });

                    temperalarmstr.append(temperAlarmStatus + ",");
                    differalarmstr.append(differAlarmStatus + ",");
                    alarmmessage.append(
                            GetAlarmMessage(temperAlarmStatus,
                                    "分区" + dtsp.getPartitionname() + "位置" + alarmlen + "m定温"));
                    alarmmessage.append(
                            GetAlarmMessage(differAlarmStatus,
                                    "分区" + dtsp.getPartitionname() + "位置" + alarmlen + "m差温"));
                    pdatastr.append(temperarray[index] + ",");
                    averagetemp += temperarray[index];
                    tlen++;
                    maximumtemp = maximumtemp > temperarray[index] ? maximumtemp : temperarray[index];
                }
            } catch (Exception e) {
                // 分区初始化
                setText(e.toString());
                setText("<" + dts.getIpaddr() + ">" + "分区数据写入失败,正在执行初始化操作...");
                for (int i = 0; i < plen; i++) {
                    if (i + Math.round(dtsp.getStartposition()) >= datalen) {
                        break;
                    }
                    temperalarmstr.append("0,");
                    differalarmstr.append("0,");
                    pdatastr.append(temperarray[i + Math.round(dtsp.getStartposition() * 2)] + ",");
                }
                dtsp.setDatalength(plen);
                dtsp.setData(pdatastr.toString());
                dtsp.setTemperalarmlevel(temperalarmstr.toString());
                dtsp.setDifferalarmlevel(differalarmstr.toString());
                dtspartitionmapper.updateByPrimaryKeySelective(dtsp);
                continue;
            }
            dtsp.setMaximumtemp(maximumtemp);
            if (tlen != 0) {
                dtsp.setAveragetemp(averagetemp / tlen);
            } else {
                dtsp.setAveragetemp(0f);
            }

            dtsp.setDatalength(plen);
            dtsp.setData(pdatastr.toString());
            dtsp.setTemperalarmlevel(temperalarmstr.toString());
            dtsp.setDifferalarmlevel(differalarmstr.toString());
            dtsp.setLastalarmlevel(alarmlevel);
            dtsp.setLastalarmmessage(alarmmessage.toString());
            dtsp.setLasthisdatatime(paddHistory(dtsp));
            dtsp.setLastdatatime(dt);
            dtsp.setPartitionname(null);
            dtsp.setStartposition(null);
            dtsp.setEndposition(null);
            dtsp.setTemperalarmvalue(null);
            dtsp.setTemperalarmrelievevalue(null);
            dtsp.setTemperwarnvalue(null);
            dtsp.setTemperwarnrelievevalue(null);
            dtsp.setDifferalarmvalue(null);
            dtsp.setDifferalarmrelievevalue(null);
            dtsp.setDifferwarnvalue(null);
            dtsp.setDifferwarnrelievevalue(null);
            dtspartitionmapper.updateByPrimaryKeySelective(dtsp);
        }
    }

    private Date addHistory(Dtssensor sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Dtssensor sensor) {
        Dtshistory his = new Dtshistory();
        his.setStationid(sensor.getStationid());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setIpaddr(sensor.getIpaddr());
        his.setIpname(sensor.getIpname());
        his.setChunk(sensor.getChunk());
        his.setPointname(sensor.getPointname());
        his.setDatatime(sensor.getLastdatatime());
        his.setData(sensor.getData());
        his.setDatalength(sensor.getDatalength());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        // 不插入这个,文本太多
        // his.setAlarmmessage(sensor.getLastalarmmessage());
        id[sensor.getChunk()] = dtsserviceimpl.AddAndGetId(his);
    }

    private Date paddHistory(Dtspartition sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                padd(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    padd(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void padd(Dtspartition sensor) {
        Dtsphistory his = new Dtsphistory();
        his.setStationid(sensor.getStationid());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setIpaddr(sensor.getIpaddr());
        his.setIpname(sensor.getIpname());
        his.setChunk(sensor.getChunk());
        his.setStartposition(sensor.getStartposition());
        his.setEndposition(sensor.getEndposition());
        his.setMaximumtemp(sensor.getMaximumtemp());
        his.setAveragetemp(sensor.getAveragetemp());
        his.setPartitionno(sensor.getPartitionno());
        his.setPartitionname(sensor.getPartitionname());
        his.setPointname(sensor.getPointname());
        his.setDatatime(sensor.getLastdatatime());
        his.setData(sensor.getData());
        his.setDatalength(sensor.getDatalength());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setMachinelength(sensor.getMachinelength());
        his.setPid(id[sensor.getChunk()]);
        // 不插入这个,文本太多
        his.setAlarmmessage(sensor.getLastalarmmessage());
        dtsphistorymapper.insertSelective(his);
    }

    @Override
    public void setDisconnected() {
        Dtssensor dts = new Dtssensor();
        dts.setIpaddr(ad.getIp());
        dts.setDevicegroup(ad.getDevicegroup());
        dts.setStationid(ad.getStationid());
        dts.setLastcommunicationstatus(1);
        dtsserviceimpl.Update(dts, false);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String cmdtype = "";
        String nametype = "";
        int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
            if (ad.getBrand().equals("1")) {// 德钢
                HttpRequestEx();
            } else {// 驭光
                if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                    addrindex = Appdevice.getAddrmin();
                if (ad.getBrand().equals("16")) {
                    cstr = "CC5500000004FF0D00" + checksum("CC5500000004FF0D00");
                    Send(cstr);
                    cstr = "";
                    Thread.sleep(timersp);
                }
                cstr = String.format(Appdevice.getCmd(), String.format("%02X", (byte) (addrindex - 1)));
                cstr += checksum(cstr);
                Send(cstr);

                if (reSend[addrindex] > 3) {
                    Dtssensor dts = new Dtssensor();
                    dts.setIpaddr(ad.getIp());
                    dts.setDevicegroup(ad.getDevicegroup());
                    dts.setStationid(ad.getStationid());
                    dts.setLastcommunicationstatus(1);
                    dts.setChunk(addrindex);
                    dtsserviceimpl.UpdateStatus(dts);
                    Dtspartition dtsp = new Dtspartition();
                    dtsp.setStationid(ad.getStationid());
                    dtsp.setDevicegroup(ad.getDevicegroup());
                    dtsp.setIpaddr(ad.getIp());
                    dtsp.setChunk(addrindex);
                    dtsp.setLastalarmlevel(2);
                    dtsp.setLastalarmmessage("设备<<" + ad.getName() + ">>通道" + addrindex + "通讯异常...请检查原因");
                    dtspartitionmapper.updatebytotal(dtsp);
                    setText("设备<<" + ad.getName() + ">>通道" + addrindex + "通讯异常...请检查原因");
                    reSend[addrindex] = 0;
                    addrindex++;
                }
                reSend[addrindex]++;
            }

            Thread.sleep(timersp);
        }
    }

    public void HttpRequestEx() {
        String url = "http://192.168.1.231:10393/mock/43ecf14d-a746-49af-b2ac-7e8730e9f046/api/v1/upload?apipost_id=c9c943";
        String deviceId = "CLKJ20231023";

        // 创建RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("DeviceId", deviceId);

        try {
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(headers),
                    String.class);

            // 获取响应体
            String responseBody = response.getBody();

            // 解析响应体中的数据
            parseParam(responseBody);

        } catch (Exception e) {
            setText("分布式光纤连接失败！");
        }
    }

    private String parseParam(String responseBody) {
        JSONObject object = JSONObject.parseObject(responseBody);
        String str = object.getString("SourceData1");
        int channel = object.getInteger("channel");
        float AvgValue = object.getFloat("AvgValue");
        float MaxValue = object.getFloat("MaxValue");
        Date UpdateTime = object.getDate("UpdateTime");
        int DeviceStatus = object.getInteger("DeviceStatus");
        Dtssensor dts = new Dtssensor();
        dts.setIpaddr(ad.getIp());
        dts.setDevicegroup(ad.getDevicegroup());
        dts.setStationid(ad.getStationid());
        dts.setLastcommunicationstatus(DeviceStatus == 1 ? 0 : 1);
        dts.setChunk(channel);
        dtsserviceimpl.UpdateStatus(dts);
        String result = str.substring(1, str.length() - 1);
        loadAllTemperAboutDegang(result, channel, AvgValue, MaxValue, UpdateTime);
        return null;
    }

    /**
     * 分布式光纤用短连接第一次不需要初始化
     *
     * @throws Exception
     */
    public boolean Initialize(Appdevice ad) {
        if (ad != null) {
            this.ad = ad;
        }
        return true;
    }

    @Async("threadPool")
    public void startReceiveThread() {
        socketConnectType = 1;// 短连接
        isrecv.put(Thread.currentThread().getId(), true);
        while (isrecv.get(Thread.currentThread().getId()) != null) {
            recvSum("");
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
